package com.e.library.http;

import com.google.gson.JsonParseException;

import org.reactivestreams.Subscriber;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

/**
 * Created by lxy on 2016/8/24 0:52.
 */
public abstract class EResponseSubscriber implements Subscriber<EResponse> {

    private EResponseListener mListener;

    public EResponseSubscriber callback(EResponseListener listener){
        this.mListener = listener;
        return this;
    }

//    @Override
//    abstract public void onStart();
//
//    @Override
//    abstract public void onCompleted();

    public void onFail(String msg){
        if (mListener == null){
            return;
        }
        mListener.onError(msg);
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof SessionExpireException){
        }else {
            onComplete();
            onFail(handleServerError(e));
        }
    }

    @Override
    public void onNext(EResponse response) {

        try{
            onComplete();
            if (mListener == null){
                return;
            }

            mListener.onFinish(response);
            if (response.isSuccess()){
                mListener.onSuccess(response);
            } else {
                onFail(response.getMessage());
            }
        }catch (Exception e){
            onError(e);
            e.printStackTrace();
        }

    }

    public String handleServerError(Throwable t){
        String msg = "系统发生错误";
        if (t instanceof TimeoutException || t instanceof SocketTimeoutException){
            msg = "请求超时了，请稍后再试";
        }else if (t instanceof UnknownHostException){
            msg = "无法访问，服务器出错了";
        }else if (t instanceof NullPointerException){
            msg = "请重新登录再试！";
        }else if (t instanceof IOException){
            msg = "网络异常，请稍后再试";
        }else if (t instanceof JsonParseException){
            msg = "数据解析出错了";
        }else if (t instanceof ClassCastException){
            msg = "数据解析出错了";
        }
        return msg;
    }
}
